<?php

namespace Xtsb\Cims\Query;

use Xtsb\Cims\Audit\Status;
use Xtsb\Cims\Branch\Branch;
use app\Http\OA\Servers\BranchServer;
use app\Http\Stats\Servers\ProjectStatsServer;
use app\Http\Storage\Servers\InventoryBusinessServer;
use think\facade\Db;
use think\Request;

class SearchHelper
{
  /**
   * @param $inventory_type 1 入库， 2 出库
   */
  public static function storageFinish($inventory_type)
  {
    return ['type' => 'select', 'name' => 'finish', 'list' => InventoryBusinessServer::getFinishList($inventory_type), 'placeholder' => $inventory_type == 1 ? '--入库进度--' : '--出库进度--',];
  }

  public static function creator()
  {
    return [
      'type' => 'select', 'name' => 'creator', 'list' =>
        [
          ['value' => 1, 'label' => '我的'],
        ], 'placeholder' => '--全部数据--',
    ];
  }

  /**
   * status 状态搜索
   * @param $list
   * @return array
   */
  public static function status($list = [1, 2, 3, 4], $table = null)
  {
    $data = [];
    if (!$list) {
      $table = $table ?? get_table_name();
      $data = Status::list($table);
    } else {
      $temp = Status::statusNames();
      foreach ($list as $item) {
        if (isset($temp[$item])) {
          $data[] = ['value' => $item, 'label' => $temp[$item]];
        }
      }
    }
    return [
      'type' => 'select', 'name' => 'status', 'list' => $data, 'placeholder' => '--审核状态--',
    ];
  }

  public static function field($list)
  {
    $data = [
      'type' => 'select', 'name' => 'field', 'list' => [], 'placeholder' => '--关键词类型--'
    ];
    foreach ($list as $value => $label) {
      $data['list'][] = [
        'value' => $value, 'label' => $label
      ];
    }
    return $data;
  }

  /**
   * 日期区间
   * @return string[]
   */
  public static function dateRange()
  {
    return ['type' => 'daterange', 'name' => 'create_time', 'start_placeholder' => '申请日期', 'end_placeholder' => ''];
  }

  /**
   * 关键词搜索
   * @return string[]
   */
  public static function keyword()
  {
    return ['type' => 'input', 'name' => 'keyword', 'placeholder' => '关键词'];
  }

  public static function oldToNew($list, $is_condition = false)
  {
    $text = "";
    foreach ($list as $each) {
      if ($each['type'] == 'select') {
        $array = '[';
        if ($is_condition) {
          $each = $each['condition'];
        }

        foreach ($each['list'] as $item) {
          $array .= "'{$item['value']}'=>'{$item['label']}',";
        }
        $array .= ']';
        $holder = $each['placeholder'] ?? "";
        $name = $each['name'] ?? $each['field_name'];
        $text .= "SearchHelper::getCustomSelect($array,'{$name}','{$holder}'),<br/>";
      }
    }
    echo $text;
    die;
  }

  public static function getCustomSelect($list, $name, $placeholder)
  {
    $data = [
      'type' => 'select', 'name' => $name, 'list' => [], 'placeholder' => "{$placeholder}"
    ];
    foreach ($list as $value => $label) {
      $data['list'][] = [
        'value' => $value, 'label' => $label
      ];
    }
    return $data;
  }

  public static function getCustomStatus($table)
  {
    return ['type' => 'select', 'name' => 'status', 'list' => Status::list($table), 'placeholder' => '审核状态'];
  }

  public static function generateStatusList()
  {
    $list = Status::LIST;
    $text = "[<br/>";
    foreach ($list as $each) {
      $text .= "{$each['id']}=>'{$each['title']}',";
    }
    $text .= "<br/>]<br/>";
    echo($text);
    die;
  }


  public static function getSqlCaseWhen($array, $field)
  {
    $text = "CASE ";
    foreach ($array as $condition => $result) {
      $text .= " WHEN {$condition} THEN '$result' ";
    }
    $text .= " ELSE '' END $field";
    return $text;
  }

  public static function pushItemInkeyInArr($list, $index)
  {
    $new_list = [];
    foreach ($list as $each) {
      $item = $each[$index];
      if (isset($new_list[$item]) == false) {
        $new_list[$item] = [];
      }
      array_push($new_list[$item], $each);
    }
    return $new_list;
  }

  public static function pushKVInArr($list, $key, $value)
  {
    $new_list = [];
    foreach ($list as $each) {
      $new_list[$each[$key]] = $each[$value];
    }
    return $new_list;
  }

  /**通过用户的输入获取制定的索引条件 并返回对应的用户前端的搜索框
   * @param $input
   * @param $search_list
   * @param $where
   * @return array
   */
  public static function appendWhereByUserInput($input, $search_list, &$where)
  {

    $user_search_list = [];
    foreach ($search_list as $search) {
      $field = $search['field'];
      $column = $search['column'];
      $placeholder = $search['placeholder'];
      $type = $search['type'] ?? "input";

      $value = $input[$field] ?? "";
      if ($column && $value) {
        if ($type == 'input') {
          $where[] = [$column, 'like', "%{$value}%"];
        } elseif ($type == 'daterange') {
          $where[] = ['between', 'between', [$value[0] . ' 00:00:00', $value[1] . ' 23:59:59']];
        }
      }

      $user_search_list[] = ['type' => $type, 'name' => $field, 'placeholder' => $placeholder];
    }

    return $user_search_list;
  }

  public static function getSearchListWhileAppendWhere(Request $request, $column_list, &$where)
  {
    $search_list = [];

    $input = $request ?: input();

    foreach ($column_list as $info) {


      $field = $info['field'];
      $column = $info['column'];
      $value = $input[$field] ?? "";

      $placeholder = $info['placeholder'] ?? "";
      $start_placeholder = $info['start_placeholder'] ?? "";
      $end_placeholder = $info['end_placeholder'] ?? "";
      $type = $info['type'] ?? "input";
      if ($placeholder) {
        $search_list[] = ['type' => $type, 'name' => $field, 'placeholder' => $placeholder];
      } elseif ($start_placeholder || $end_placeholder) {
        $search_list[] = ['type' => $type, 'name' => $field, 'start_placeholder' => $start_placeholder, 'end_placeholder' => $end_placeholder];
      }


      $expression = $info['exp'] ?? "=";


      if ($value && $expression == "=") {
        $value = $value == 'null' ? null : trim($value);
        $where[] = [$column, '=', $value];

      } elseif ($value && $expression == 'like') {
        $where[] = [$column, 'like', "%" . trim($value) . "%"];

      } elseif ($value && $expression == 'between time') {
        $where[] = [$column, $expression, [$value[0] . " 00:00:00", $value[1] . " 23:59:59"]];

      } elseif ($value && $expression == 'between') {
        $where[] = [$column, $expression, [$value[0], $value[1]]];

      }

    }

    return $search_list;
  }

  public static function getYearListWhileAppendWhere(Request $request, &$where)
  {
    $dm_id = trim($request->param('dm_id'));

    if ($request->param('year')) {
      $year = $request->param('year');
      $start_date = $year . '-01-01';
      $end_date = $year . '-12-31';
      $where[] = ['c.start_date|c.sign_date', '<=', $end_date];
      $where[] = ['c.end_date', '>=', $start_date];
    }

    return ProjectStatsServer::getCcaYearList($dm_id);
  }

  public static function searchBranchAndDm()
  {
    return [
      ['type' => 'cascader', 'name' => 'branch_id', 'placeholder' => '机构',
        'list' => BranchServer::list([
          ['id', 'IN', Branch::getAllSubBranch()]
        ]),
        'request' => [
          'url' => 'xtsb/Dm/get/OA',
          'querys' => [
            ['name' => 'branch_id', 'value' => 'branch_id']
          ],
          'setData' => 'dm_list'
        ]
      ],
      ['type' => 'select', 'name' => 'dm_id', 'placeholder' => '部门(选择机构后可选)', 'list' => 'dm_list']
    ];
  }

  public static function getDmByLeader()
  {
    $list = Db::name("dm")->where([['manager_id|leader_id', '=', UID]])->distinct(true)->column("title", 'id');
    $search = [];
    if ($list) {
      $search[] = SearchHelper::getCustomSelect($list, 'dm_id', '部门选择');
    }
    return $search;
  }

  const FIELD_COMMON = "g.id,g.creator,g.handler,g.status,s1.name creator_name,s2.name handler_name,g.create_time,";

  public static function amountTypeSearch(&$search, $amount_field_list)
  {
    $amount_field_data = [];
    $all_key = '';
    foreach ($amount_field_list as $key => $val) {
      $amount_field_data[$key] = $val;
      $all_key = $all_key ? $all_key . '|' . $key : $key;
    }
    if ($all_key && count($amount_field_list) > 1) {
      $amount_field_data[$all_key] = '以上任意金额';
    }

    $amount_search_type_str = input('amount_search_type');
    $search[] = ['type' => 'select', 'name' => 'amount_search_type', 'list' => [
      ['value' => '1/' . $all_key, 'label' => '金额准确查询'],
      ['value' => '2/' . $all_key, 'label' => '金额范围查询'],
    ], 'placeholder' => '--金额查询方式--'];
    $amount_search_type_arr = explode('/', $amount_search_type_str);
    if (!$amount_search_type_arr || empty($amount_search_type_arr)) {
      $amount_search_type = 0;
    } else {
      $amount_search_type = $amount_search_type_arr[0];
    }

    if ($amount_search_type == 1) {
      $search[] = SearchHelper::getCustomSelect($amount_field_data, 'amount_field', '--金额类型--');
      $search[] = ['type' => 'input', 'name' => 'amount_keyword', 'placeholder' => '金额'];
    } else if ($amount_search_type == 2) {
      $search[] = SearchHelper::getCustomSelect($amount_field_data, 'amount_field', '--金额类型--');
      $search[] = ['type' => 'input', 'name' => 'amount_keyword_start', 'placeholder' => '金额下限'];
      $search[] = ['type' => 'input', 'name' => 'amount_keyword_end', 'placeholder' => '金额上限'];
    }

    return true;
  }

  //构造搜索页面的机构、部门筛选项
  public static function appendBranchSearch(&$search, $index = null)
  {

    $branch_field = ['type' => 'cascader', 'name' => 'branch_id', 'placeholder' => '机构',
      'list' => BranchServer::list([
        ['id', 'IN', Branch::getAllSubBranch()]
      ]),
      'request' => [
        'url' => 'xtsb/Dm/get/OA',
        'querys' => [
          ['name' => 'branch_id', 'value' => 'branch_id']
        ],
        'setData' => 'dm_list'
      ]
    ];
    $dm_field = ['type' => 'select', 'name' => 'dm_id', 'placeholder' => '部门', 'list' => 'dm_list'];
    if (isset($index)) {
      array_splice($search, $index, 0, [$dm_field]);
      array_splice($search, $index, 0, [$branch_field]);
    } else {
      $search[] = $branch_field;
      $search[] = $dm_field;
    }

  }

  //构造where查询条件中的机构、部门数据
  public static function appendBranchWhere(&$where, $alias = 'g')
  {
    $branch_id = (int)input('branch_id');
    if ($branch_id) {
      $dm_id = (int)input('dm_id');
      if ($dm_id)
        $where[] = [$alias . '.dm_id', '=', $dm_id];
      else {
        $where[] = [$alias . '.branch_id', 'in', Branch::getAllSubBranch(false, 10, $branch_id)];
      }
    }
  }

  //材料管理-材料信息搜索
  public static function goodsTitleSearch(&$search)
  {
    $search[] = ['type' => 'input', 'name' => 'goods_title', 'placeholder' => '材料信息'];

    return true;
  }
}